package dbclass;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import classes.DbClass;

import beans.Comentario;

public class ComentarioJDBC implements ComentarioDAO{	

	private Connection con;
	
	
	public Comentario insert(Comentario comentario) throws SQLException, ClassNotFoundException
	{
		con = DbClass.getConnection();
		Statement stm = con.createStatement();
		
		boolean check =  stm.execute("INSERT INTO comentario (id, corpo, data, id_noticia) VALUES (" +
				"NULL, '" + comentario.getCorpo() + "', '" + comentario.getData()+ "', '" + comentario.getId_noticia() + "')");
		
		
		if(check)
		{
			return comentario;
		}	
		return null;	
	}
	
	public Comentario update(Comentario comentario) throws SQLException, ClassNotFoundException
	{
		con = DbClass.getConnection();
		Statement stm = con.createStatement();
		
		boolean check = stm.execute("UPDATE comentario SET corpo = '" + comentario.getCorpo() + "', data = '" + comentario.getData() +
				"', id_noticia = '" + comentario.getId_noticia() + "' WHERE id = '" + comentario.getId() + "'");
		
		if(check)
		{
			return comentario;
		}	
		return null;
	}

	public boolean delete(long id) throws ClassNotFoundException, SQLException {
		con = DbClass.getConnection();
		Statement stm = con.createStatement();
		
		int check = stm.executeUpdate("DELETE FROM comentario WHERE id = '" + id + "' LIMIT 1");
		if(check > 0)
			return true;
		return false;
	}

	public List<Comentario> findAll() throws SQLException, ClassNotFoundException {
		List<Comentario> comentarioes = new ArrayList<Comentario>();
		
		con = DbClass.getConnection();
		Statement stm = con.createStatement();
		
		ResultSet result;
		result = stm.executeQuery("SELECT * FROM comentario");
		
		while (result.next()) {
			Comentario comentario = new Comentario(result.getLong(1), result.getString(2), result.getString(3), result.getLong(4));
            comentarioes.add(comentario);
        }		
		return comentarioes;
	}


	public Comentario findById(long id) throws SQLException, ClassNotFoundException {
		Comentario comentario = null;
		
		con = DbClass.getConnection();
		Statement stm = con.createStatement();
		
		ResultSet result;
		result = stm.executeQuery("SELECT * FROM comentario WHERE id = '" + id + "'");
		
		while (result.next()) {
			comentario = new Comentario(result.getLong(1), result.getString(2), result.getString(3), result.getLong(4));
        }		
		return comentario;
	}

}